package per.vic.attachment.dao;

import org.springframework.jdbc.core.PreparedStatementCreator;
import per.vic.attachment.constant.AttachmentConstant;
import per.vic.attachment.model.Attachment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-01-13 10:23
 */
public class OracleAttachmentDao extends BaseAttachmentDao {

    @Override
    public Attachment insert(Attachment attachment) {
        String sql = "insert into " + AttachmentConstant.ATTACHMENT_TABLE
                + " (absolute_path, relative_path, temporary, module,content_type, file_size, file_name, original_name,create_time, id) "
                + " values (?, ?, 1, ?, ?, ?, ?, ?, sysdate, ?)";
        Integer id = getNextId();
        attachment.setId(id);
        jdbcTemplate.update(new PreparedStatementCreator() {

            @Override
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setString(1, attachment.getAbsolutePath());
                ps.setString(2, attachment.getRelativePath());
                ps.setString(3, attachment.getModule());
                ps.setString(4, attachment.getContentType());
                ps.setInt(5, attachment.getSize());
                ps.setString(6, attachment.getFilename());
                ps.setString(7, attachment.getOriginalName());
                ps.setInt(8, id);
                return ps;
            }
        });
        return attachment;
    }


    /**
     * 获取下一个插入的数据的id
     * @return
     */
    private synchronized int getNextId() {
        String sql = "select max(id) from  attachment a";

        Integer currentMax = jdbcTemplate.queryForObject(sql, Integer.class);
        if (currentMax == null) {
            return 1;
        }
        return currentMax.intValue() + 1;

    }
}
